/**
 * 多端平台适配工具类
 */

// 获取当前平台信息
export const getPlatform = () => {
  // #ifdef APP-PLUS
  return 'app'
  // #endif
  
  // #ifdef MP-WEIXIN
  return 'mp-weixin'
  // #endif
  
  // #ifdef H5
  return 'h5'
  // #endif
  
  // #ifdef MP-ALIPAY
  return 'mp-alipay'
  // #endif
  
  // #ifdef MP-BAIDU
  return 'mp-baidu'
  // #endif
  
  // #ifdef MP-TOUTIAO
  return 'mp-toutiao'
  // #endif
  
  return 'unknown'
}

// 判断是否为小程序环境
export const isMiniProgram = () => {
  const platform = getPlatform()
  return platform.startsWith('mp-')
}

// 判断是否为APP环境
export const isApp = () => {
  return getPlatform() === 'app'
}

// 判断是否为H5环境
export const isH5 = () => {
  return getPlatform() === 'h5'
}

// 判断是否为微信小程序
export const isWeixinMiniProgram = () => {
  return getPlatform() === 'mp-weixin'
}

// 兼容性别名
export const isMpWeixin = isWeixinMiniProgram

// 判断是否在微信浏览器中
export const isWeChat = () => {
  // #ifdef H5
  const ua = navigator.userAgent.toLowerCase()
  return ua.includes('micromessenger')
  // #endif
  
  // #ifdef MP-WEIXIN
  return true
  // #endif
  
  return false
}

// 获取系统信息
export const getSystemInfo = () => {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: (res) => {
        resolve({
          ...res,
          platform: getPlatform(),
          isMiniProgram: isMiniProgram(),
          isApp: isApp(),
          isH5: isH5()
        })
      },
      fail: reject
    })
  })
}

// 获取状态栏高度
export const getStatusBarHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  return systemInfo.statusBarHeight || 0
}

// 获取导航栏高度
export const getNavBarHeight = () => {
  const platform = getPlatform()
  const statusBarHeight = getStatusBarHeight()
  
  if (platform === 'app') {
    return statusBarHeight + 44
  } else if (platform === 'mp-weixin') {
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    return menuButtonInfo.bottom + menuButtonInfo.top - statusBarHeight
  } else if (platform === 'h5') {
    return statusBarHeight + 44
  }
  
  return 44
}

// 获取底部安全区域高度
export const getSafeAreaBottom = () => {
  const systemInfo = uni.getSystemInfoSync()
  const safeArea = systemInfo.safeArea
  const screenHeight = systemInfo.screenHeight
  
  if (safeArea && safeArea.bottom) {
    return screenHeight - safeArea.bottom
  }
  
  return 0
}

// 获取安全区域信息
export const getSafeArea = () => {
  const systemInfo = uni.getSystemInfoSync()
  const safeArea = systemInfo.safeArea || {}
  
  return {
    top: safeArea.top || 0,
    right: safeArea.right || systemInfo.windowWidth || 0,
    bottom: safeArea.bottom || systemInfo.windowHeight || 0,
    left: safeArea.left || 0,
    width: safeArea.width || systemInfo.windowWidth || 0,
    height: safeArea.height || systemInfo.windowHeight || 0
  }
}

// 平台特定的页面跳转
export const navigateTo = (options) => {
  const platform = getPlatform()
  
  if (platform === 'h5' && options.url.includes('?')) {
    // H5环境下处理路由参数
    options.url = options.url.replace(/\?/g, '&').replace(/&/, '?')
  }
  
  return uni.navigateTo(options)
}

// 平台特定的分享功能
export const share = (options) => {
  const platform = getPlatform()
  
  if (platform === 'mp-weixin') {
    // 微信小程序分享
    return uni.share({
      provider: 'weixin',
      scene: 'WXSceneSession',
      ...options
    })
  } else if (platform === 'app') {
    // APP分享
    return uni.share({
      provider: 'weixin',
      ...options
    })
  } else if (platform === 'h5') {
    // H5分享（使用Web Share API或自定义分享）
    if (navigator.share) {
      return navigator.share(options)
    } else {
      // 降级处理：复制链接到剪贴板
      uni.setClipboardData({
        data: options.href || window.location.href,
        success: () => {
          uni.showToast({
            title: '链接已复制到剪贴板',
            icon: 'success'
          })
        }
      })
    }
  }
}

// 平台特定的存储
export const setStorage = (key, data) => {
  const platform = getPlatform()
  
  if (platform === 'h5') {
    // H5环境下使用localStorage
    try {
      localStorage.setItem(key, JSON.stringify(data))
      return Promise.resolve()
    } catch (e) {
      return Promise.reject(e)
    }
  } else {
    // 其他平台使用uni.setStorage
    return new Promise((resolve, reject) => {
      uni.setStorage({
        key,
        data,
        success: resolve,
        fail: reject
      })
    })
  }
}

export const getStorage = (key) => {
  const platform = getPlatform()
  
  if (platform === 'h5') {
    // H5环境下使用localStorage
    try {
      const data = localStorage.getItem(key)
      return Promise.resolve(data ? JSON.parse(data) : null)
    } catch (e) {
      return Promise.reject(e)
    }
  } else {
    // 其他平台使用uni.getStorage
    return new Promise((resolve, reject) => {
      uni.getStorage({
        key,
        success: (res) => resolve(res.data),
        fail: reject
      })
    })
  }
}

// 平台特定的网络请求配置
export const getRequestConfig = () => {
  const platform = getPlatform()
  
  const baseConfig = {
    timeout: 60000,
    header: {
      'Content-Type': 'application/json'
    }
  }
  
  if (platform === 'mp-weixin') {
    // 微信小程序特定配置
    return {
      ...baseConfig,
      header: {
        ...baseConfig.header,
        'X-Platform': 'mp-weixin'
      }
    }
  } else if (platform === 'app') {
    // APP特定配置
    return {
      ...baseConfig,
      header: {
        ...baseConfig.header,
        'X-Platform': 'app'
      }
    }
  } else if (platform === 'h5') {
    // H5特定配置
    return {
      ...baseConfig,
      header: {
        ...baseConfig.header,
        'X-Platform': 'h5'
      }
    }
  }
  
  return baseConfig
}

// 平台特定的图片选择
export const chooseImage = (options = {}) => {
  const platform = getPlatform()
  
  const defaultOptions = {
    count: 9,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera']
  }
  
  if (platform === 'mp-weixin') {
    // 微信小程序使用chooseMedia
    return uni.chooseMedia({
      count: options.count || defaultOptions.count,
      mediaType: ['image'],
      sourceType: options.sourceType || defaultOptions.sourceType,
      camera: 'back'
    })
  } else {
    // 其他平台使用chooseImage
    return uni.chooseImage({
      ...defaultOptions,
      ...options
    })
  }
}

// 平台特定的文件上传
export const uploadFile = (options) => {
  const platform = getPlatform()
  const requestConfig = getRequestConfig()
  
  return uni.uploadFile({
    ...options,
    header: {
      ...requestConfig.header,
      ...options.header
    }
  })
}

export default {
  getPlatform,
  isMiniProgram,
  isApp,
  isH5,
  isWeixinMiniProgram,
  isMpWeixin,
  isWeChat,
  getSystemInfo,
  getStatusBarHeight,
  getNavBarHeight,
  getSafeAreaBottom,
  getSafeArea,
  navigateTo,
  share,
  setStorage,
  getStorage,
  getRequestConfig,
  chooseImage,
  uploadFile
}
